"""
产品管理服务类
负责产品的CRUD操作和Stripe产品同步
"""

import stripe
import uuid
import logging
from datetime import datetime
from typing import Optional, Dict, Any, List
from fastapi import HTTPException

from utils.config import Config
from utils.data_store import DataStore
from models.product_models import ProductCreateRequest, ProductUpdateRequest

logger = logging.getLogger(__name__)


class ProductService:
    """产品管理服务类"""
    
    def __init__(self):
        self.products = DataStore.load_data(Config.PRODUCTS_FILE)
    
    def create_product(self, request: ProductCreateRequest) -> Dict[str, Any]:
        """创建新产品和价格"""
        # 检查产品名称是否已存在
        for product_id, product_data in self.products.items():
            if product_data.get('name') == request.name:
                raise HTTPException(
                    status_code=400, 
                    detail=f"产品名称 '{request.name}' 已存在"
                )
        
        try:
            # 创建Stripe产品
            stripe_product = stripe.Product.create(
                name=request.name,
                description=request.description,
                metadata=request.metadata or {}
            )
            
            # 创建Stripe价格
            stripe_price = stripe.Price.create(
                product=stripe_product.id,
                unit_amount=request.unit_amount,
                currency=request.currency,
                recurring={
                    "interval": request.interval,
                    "interval_count": request.interval_count
                },
                metadata=request.metadata or {}
            )
            
            # 生成本地产品ID
            local_product_id = str(uuid.uuid4())
            
            # 构建产品数据
            product_data = {
                'id': local_product_id,
                'stripe_product_id': stripe_product.id,
                'stripe_price_id': stripe_price.id,
                'name': request.name,
                'description': request.description,
                'unit_amount': request.unit_amount,
                'currency': request.currency,
                'interval': request.interval,
                'interval_count': request.interval_count,
                'metadata': request.metadata or {},
                'created_at': datetime.now().isoformat(),
                'updated_at': datetime.now().isoformat(),
                'is_active': True
            }
            
            # 保存到本地存储
            self.products[local_product_id] = product_data
            DataStore.save_data(Config.PRODUCTS_FILE, self.products)
            
            logger.info(f"产品创建成功: {local_product_id} - {request.name}")
            return product_data
            
        except stripe.error.StripeError as e:
            logger.error(f"Stripe错误: {str(e)}")
            raise HTTPException(status_code=400, detail=f"Stripe错误: {str(e)}")
        except Exception as e:
            logger.error(f"创建产品失败: {str(e)}")
            raise HTTPException(status_code=500, detail="创建产品失败")
    
    def get_product(self, product_id: str) -> Optional[Dict[str, Any]]:
        """获取产品信息"""
        return self.products.get(product_id)
    
    def list_products(self, limit: int = 100, offset: int = 0) -> List[Dict[str, Any]]:
        """列出产品"""
        products_list = list(self.products.values())
        return products_list[offset:offset + limit]
    
    def update_product(self, product_id: str, request: ProductUpdateRequest) -> Optional[Dict[str, Any]]:
        """更新产品信息"""
        if product_id not in self.products:
            return None
        
        product_data = self.products[product_id]
        
        # 检查产品名称是否被其他产品使用
        if request.name and request.name != product_data.get('name'):
            for pid, pdata in self.products.items():
                if pid != product_id and pdata.get('name') == request.name:
                    raise HTTPException(
                        status_code=400, 
                        detail=f"产品名称 '{request.name}' 已被其他产品使用"
                    )
        
        try:
            # 更新Stripe产品
            update_data = {}
            if request.name:
                update_data['name'] = request.name
            if request.description is not None:
                update_data['description'] = request.description
            if request.metadata is not None:
                update_data['metadata'] = request.metadata
            
            if update_data:
                stripe.Product.modify(
                    product_data['stripe_product_id'],
                    **update_data
                )
            
            # 更新本地数据
            for key, value in update_data.items():
                product_data[key] = value
            
            product_data['updated_at'] = datetime.now().isoformat()
            self.products[product_id] = product_data
            DataStore.save_data(Config.PRODUCTS_FILE, self.products)
            
            logger.info(f"产品更新成功: {product_id}")
            return product_data
            
        except stripe.error.StripeError as e:
            logger.error(f"Stripe错误: {str(e)}")
            raise HTTPException(status_code=400, detail=f"Stripe错误: {str(e)}")
        except Exception as e:
            logger.error(f"更新产品失败: {str(e)}")
            raise HTTPException(status_code=500, detail="更新产品失败")
    
    def delete_product(self, product_id: str) -> bool:
        """删除产品"""
        if product_id not in self.products:
            return False
        
        product_data = self.products[product_id]
        
        try:
            # 删除Stripe价格和产品
            stripe.Price.modify(product_data['stripe_price_id'], active=False)
            stripe.Product.modify(product_data['stripe_product_id'], active=False)
            
            # 从本地存储中删除
            del self.products[product_id]
            DataStore.save_data(Config.PRODUCTS_FILE, self.products)
            
            logger.info(f"产品删除成功: {product_id}")
            return True
            
        except stripe.error.StripeError as e:
            logger.error(f"Stripe错误: {str(e)}")
            raise HTTPException(status_code=400, detail=f"Stripe错误: {str(e)}")
        except Exception as e:
            logger.error(f"删除产品失败: {str(e)}")
            raise HTTPException(status_code=500, detail="删除产品失败")
    
    def reload_data(self):
        """重新加载数据"""
        self.products = DataStore.load_data(Config.PRODUCTS_FILE)
